//
//  TerminalWindow.m
//  iTerm
//
//  Created by Steve Gehrman on Fri Aug 15 2003.
//  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//

#import <PSMTabBarControl/PSMTabBarControl.h>
#import "Bookmark.h"
#import "CommuniqueController.h"
#import "TerminalWindowSession.h"
#import "TerminalWindow.h"
#import "ITSessionMgr.h"
//#import "PTYSession.h"

@implementation TerminalWindow

- (void)awakeFromNib
{	
	NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
	[center addObserver:self 
			   selector:@selector(applicationWillTerminate:) 
				   name:NSApplicationWillTerminateNotification 
				 object:NSApp];	
	
	_identifier = 0;
	
	// window
	[[self window] setBackingType:NSBackingStoreBuffered];
	if ([[self window] respondsToSelector:@selector(setBottomCornerRounded:)])
		[[self window] setBottomCornerRounded:NO];
	[[self window] setDelegate:self];
	
	NSSize size = [VT100Screen requireSizeWithFont: [[NSFont userFixedPitchFontOfSize:10] retain]];
	NSLog(@"[width = %f; height = %f]", size.width, size.height);
	[[self window] setResizeIncrements:size];
	
	//NSRect frame = [[self window] frame];
	//NSLog(@"[width = %f; height = %f]", frame.size.width, frame.size.height);
	
	//int hBorder = (8*2);
	//int vBorder = (4*2);
	
	//frame.size.width = (round((frame.size.width-hBorder)/size.width)*size.width)+hBorder;
	//frame.size.height = (round((frame.size.height-vBorder)/size.height)*size.height)+vBorder;
	
	//NSLog(@"[width = %f; height = %f]", frame.size.width, frame.size.height);
	
    //[[self window] setFrame:frame display:YES animate:YES];
	
	// toolbar
	[_toolbar setDelegate:self];
	
	// tab bar
	[_tabBar setStyleNamed:@"Metal"];
	[_tabBar setShowAddTabButton:YES]; // hmmm this doesn't work!?
    [_tabBar showAddTabButton];

    [[_tabBar addTabButton] setTarget:self];
    [[_tabBar addTabButton] setAction:@selector(createTab:)];
	
	// tab view
	[_tabBar setDelegate:self];
    
    // remove any tabs present in the nib
    NSArray *existingItems = [_tabView tabViewItems];
    NSEnumerator *e = [existingItems objectEnumerator];
    NSTabViewItem *item;
    while(item = [e nextObject]){
        [_tabView removeTabViewItem:item];
    }
		
	_sessions  = [[NSMutableArray alloc] init];
		
	[self createTab:nil];
}

- (IBAction)newTab:(id)sender
{
	[self createTab:nil];
}

- (IBAction)close:(id)sender
{
	[[self window] close];
}

- (IBAction)closeTab:(id)sender
{
	[_tabView removeTabViewItem:[_tabView selectedTabViewItem]];
	[self tabView:_tabView didCloseTabViewItem:[_tabView selectedTabViewItem]];
	if ([_tabView numberOfTabViewItems]==0) {
		[self close:self];		
	}
}

- (IBAction)showBookmarks:(id)sender
{
	CommuniqueController * cc = [[CommuniqueController alloc] init];
	[cc dockMenuManageBookmarks:sender];
}

- (NSTabViewItem*)createTabItem:(NSString*)name
{
	//int index = [_tabView numberOfTabViewItems];
	//NSNumber *number = [NSNumber numberWithInt:index];
	NSString *title = [NSString stringWithFormat:@"%@", name];	
	
	NSTabViewItem *aTabViewItem = [[[NSTabViewItem alloc] initWithIdentifier: title] autorelease];
	[aTabViewItem setLabel: title];
	[aTabViewItem setIdentifier:[NSString stringWithFormat:@"%d", _identifier]];
	[_tabView addTabViewItem:aTabViewItem];
	[_tabView selectTabViewItem:aTabViewItem];	
	
	return aTabViewItem;
}

- (PTYSession*)createPTYSession:(NSString*)command withView:(NSView*) view;
{	
	PTYSession* ptySession = [[ITSessionMgr sharedInstance] createSession:view];
    ITSessionDesc *sessionDesc = [ITSessionDesc defaultDesc];
	NSString* directory = [sessionDesc directory];
	NSDictionary *env = [NSDictionary dictionaryWithObject:directory forKey:@"PWD"];
	
	NSArray *arg;
	NSString* cmd;
	
    [ITSessionMgr breakDown:command cmdPath:&cmd cmdArgs:&arg];	
		
	[ptySession startProgram:cmd
				   arguments:arg
				 environment:env];
	
	return ptySession;	
}

- (TerminalWindowSession*) createTab:(Bookmark *)bookmark {
	[[self window] makeKeyAndOrderFront:self];
	
	NSTabViewItem *aTabViewItem = nil;
	PTYSession* ptySession = nil;
	TerminalWindowSession * session = [[TerminalWindowSession alloc] init];
	
	if (bookmark==nil) {
		aTabViewItem = [self createTabItem:@"Local"];		
		ptySession = [self createPTYSession:[[ITSessionDesc defaultDesc] command] withView:[aTabViewItem view]];
		session.ssh = FALSE;
	} else {
		aTabViewItem = [self createTabItem:bookmark.name];	
		ptySession = [self createPTYSession:[bookmark sshCommand] withView:[aTabViewItem view]];
		session.bookmark = bookmark;
		session.ssh = TRUE;
	}
	
	session.identifier = _identifier;
	[session setTabViewItem:aTabViewItem];
	[session setPTYSession:ptySession];
	
	_identifier++;
	
	[_sessions addObject:session];
	
	_currentSession = session;
	
	return session;
}

- (TerminalWindowSession *) currentSession
{
    return _currentSession;
}

-(TerminalWindowSession *) findSessionFromTabViewItem:(NSTabViewItem*)tabViewItem 
{	
	NSEnumerator *e = [_sessions objectEnumerator];
	TerminalWindowSession *w;
	while (w = [ e nextObject ]) {
		if (w.tabViewItem == tabViewItem) {
			return w;
		}
	}
	return nil;
}

- (void)closeAllSessions
{
	NSEnumerator *e = [_sessions objectEnumerator];
	TerminalWindowSession *w;
	while (w = [ e nextObject ]) {
		[w terminate];
	}
}

- (BOOL)validateMenuItem:(NSMenuItem *)item
{
	NSLog(@"%@", item);
	return YES;
}

#pragma mark -
#pragma mark ---- Window Delegates ----

- (void)applicationWillTerminate:(NSNotification *)note 
{
	[self closeAllSessions];
}

-(BOOL)windowShouldClose:(id)window
{
	[self closeAllSessions];
	return YES;
}


#pragma mark -
#pragma mark ---- Toolbar ----

/*- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag 
{
    itemForItemIdentifier
	
	NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
    
    if([itemIdentifier isEqualToString:@"TabField"]){
        [item setPaletteLabel:@"Tab Label"]; 
        [item setLabel:@"Tab Label"]; 
        [item setView:tabField];
        [item setMinSize:NSMakeSize(100, [tabField frame].size.height)];
        [item setMaxSize:NSMakeSize(500, [tabField frame].size.height)];
        
    } else if([itemIdentifier isEqualToString:@"DrawerItem"]){
        [item setPaletteLabel:@"Configuration"]; 
        [item setLabel:@"Configuration"]; 
        [item setToolTip:@"Configuration"];
        [item setImage:[NSImage imageNamed:@"32x32_log"]];
        [item setTarget:drawer]; 
        [item setAction:@selector(toggle:)];
        
    }
    
    return [item autorelease];
}

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar 
{
    return [NSArray arrayWithObjects:@"TabField",
			NSToolbarFlexibleSpaceItemIdentifier,
			@"DrawerItem",
			nil];
}

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar 
{
    return [NSArray arrayWithObjects:@"TabField",
			NSToolbarFlexibleSpaceItemIdentifier,
			@"DrawerItem",
			nil];
}*/

- (BOOL)validateToolbarItem:(NSToolbarItem *)theItem
{
    return YES;
}

#pragma mark -
#pragma mark ---- PSMTabBarControl/TabView delegates ----

- (BOOL)tabView:(NSTabView *) aTabView shouldCloseTabViewItem:(NSTabViewItem *)tabViewItem {
	//NSLog (@"%@", [tabViewItem identifier]);
	// TODO - add confirmation
	
	return YES;
}

- (void)tabView:(NSTabView *) aTabView willCloseTabViewItem:(NSTabViewItem *)tabViewItem{
	//NSLog (@"%@", [tabViewItem identifier]);
}

- (void)tabView:(NSTabView *) aTabView didCloseTabViewItem:(NSTabViewItem *)tabViewItem
{
	TerminalWindowSession*w = [self findSessionFromTabViewItem:tabViewItem];
	[w terminate];
	[_sessions removeObject:w];
}

 
@end
